<?php
abstract class My_EventPublisher_Abstract implements My_EventPublisher_Interface
{

    /**
     * Observers list
     * @var array
     */
    protected  $observers = array ();

    /**
     * Events description. Assoc array "event"=>"Description"
     * @var array
     */
    protected $eventsDescriptions = array();

    /**
     * Attach an observer
     * @param My_Observer_Interface $observer
     * @return My_EventPublisher_Interface
     */
    public function attachObserver($observer)
    {
        $observerClass = get_class($observer);
        if (!isset ($this->observers[$observerClass]))
        {
            $this->observers[$observerClass] = $observer;
        }
        return $this;
    }

    /**
     * Dettach an observer
     * @param My_Observer_Interface $observer
     * @return My_EventPublisher_Interface
     */
    public function dettachObserver($observer)
    {
        $observerClass = get_class($observer);
        if (isset ($this->observers[$observerClass]))
        {
            unset ($this->observers[$observerClass]);
        }
        return $this;
    }


    /**
     * Publish events
     * @param string $event
     * @return My_EventPublisher_Interface
     */
    public function publish($event)
    {
        if (is_array($this->observers) && sizeof($this->observers)>0)
        {
            foreach ($this->observers as $observer)
            {
                $observer->update($event, $this);
            }
        }
        return $this;
    }

    /**
     * Get event descriptions.
     * @param string $event
     * @return string
     */
    public function  getEventDescription($event)
    {
        if (isset ( $this->eventsDescriptions[$event]))
        {
            return $this->eventsDescriptions[$event];
        }
        throw new Exception('No event description avaliable for: '.$event);
    }
}
